/**
 * 20220303: dynamic importing and loading assets...jordia
 * 20220310：since no longer support [array-input],remove [object->array] converting
 */
import AssetsLoader from './assets-loader';

const setAssetsUrl=(getUrl)=>{
    return new Promise((resolve,reject)=>{
        let url=getUrl();
        resolve(url);
    })
};

/**
 * load assets
 * @param {ThreeContainer} threeContainer a container to receive and handle loading events 
 * @param {Object} loaderOut an object to store the AssetsLoader instance
 * @param {function} getURL a function to get all assets urls,the value returned could be
 *                   an object:
 *                               {
 *                                   point:import('../../assets/textures/point.png'),
 *                                   lightCube:[ import('../../assets/textures/lightCube/px.png'),...],
 *                               };
 *                   or a class instance:
 *                               new class Assets{
 *                                          model=import('../../assets/models/model.glb');
 *                                          lightCube=[ import('../../assets/textures/lightCube/px.png'),...];
 *                                   };
 *                           
 *                      
 */
const assetsLoad=async (threeContainer,loaderOut,getURL)=>{

    let assetsInfo;
    await setAssetsUrl(getURL).then((md)=>{
        assetsInfo=md;
    });
    
    for(let key in assetsInfo){
        const info=assetsInfo[key];
        if(Array.isArray(info)){
            for(let j=0;j<info.length;j++){
                await info[j].then((m)=>{info[j]=m.default;});
            }
        }else{
            await info.then((m)=>{assetsInfo[key]=m.default;});
        }
    }
    let loader=new AssetsLoader().setTargets(assetsInfo);
    loaderOut.assetsLoader=loader;
    return new Promise((resolve,reject)=>{
        loader.onLoadStart=()=>{
            threeContainer.startLoad();
        };
        loader.onLoading=(info,prg)=>{
            threeContainer.loading("资源"+ info.name +"加载中…",prg);
        };
        loader.onError=(err)=>{
            reject();
            threeContainer.loadError("["+err.join(",")+"] 加载错误！");
        };
        loader.onLoaded=()=>{
            resolve();
            setTimeout(()=>{
                threeContainer.loaded();
            },100)
        };

        loader.startLoad();
    });

};


export default assetsLoad;